<template>
  <view class="classlist">
    <view class="content">
      <navigator v-for="item in classify" class="item" :key="item._id" :url="`/pages/preview/preview?id=${item._id}`">
        <image :src="item.smallPicurl" mode="aspectFill"></image>
      </navigator>
    </view>

    <view class="layOut" v-if="classify.length || !noData">
      <uni-load-more :status="noData?'noMore':'loading'"></uni-load-more>
    </view>

    <view class="safe-area-inset-bottom"></view>
  </view>
</template>

<script setup>
  import {
    onLoad,
    onUnload,
    onReachBottom,
    onPullDownRefresh
  } from '@dcloudio/uni-app'
  import {
    ref
  } from 'vue';
  import {
    apiGetClassifyDetail,
    apiGetHistory
  } from '@/api/api.js'
  const classify = ref([])
  const noData = ref(false)
  const queryParams = {
    pageNum: 1,
    pageSize: 12
  }
  const getClassifyDetail = async (obj) => {
    let res
    if (obj.classid) res = await apiGetClassifyDetail(obj)
    if (obj.type) res = await apiGetHistory(obj)
    classify.value = [...classify.value, ...res.data]
    // 判断是否还有数据
    if (queryParams.pageSize > res.data.length) noData.value = true
    //缓存存储
    uni.setStorageSync("storgClassList", classify.value)
  }
  // onLoad执行晚于setup内部api调用
  let pageName
  onLoad((e) => {
    let {
      id = null, name = null, type = null
    } = e
    if (type) {
      queryParams.type = type
    }
    if (id) {
      queryParams.classid = id
    }
    pageName = name
    getClassifyDetail(queryParams)
    uni.setNavigationBarTitle({
      title: pageName
    })
  })
  //触底加载--无数据不执行
  onReachBottom(() => {
    if (noData.value) return
    queryParams.pageNum++
    getClassifyDetail(queryParams)
  })
  //下拉刷新
  onPullDownRefresh(() => {
    queryParams.pageNum++
    queryParams.pageSize = 12
    classify.value = []
    noData.value = false
    getClassifyDetail(queryParams)
    uni.stopPullDownRefresh()
  })
  //离开页面清除缓存
  onUnload(() => {
    uni.removeStorageSync("storgClassList")
  })
</script>

<style lang="scss" scoped>
  .classlist {
    .content {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 5rpx;
      padding: 5rpx;

      .item {
        height: 440rpx;

        image {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
    }
  }

  .layOut {
    padding: 30rpx 0;
  }
</style>